<template>
  <div class="order-detail">
    <div class="container">
      <h1>订单详情</h1>

      <div v-if="loading" class="loading">加载中...</div>
      <div v-else-if="error" class="error">{{ error }}</div>
      <div v-else-if="!order" class="empty">未找到订单</div>
      <div v-else class="detail-card">
        <!-- 状态流程提示 -->
        <div class="status-flow">
          <div class="step" :class="{ active: order.status === 1, done: order.status !== 1 }">
            <div class="icon">🕒</div>
            <div class="text">待支付</div>
          </div>
          <div class="arrow">→</div>
          <div class="step" :class="{ active: order.status === 2 }">
            <div class="icon">✅</div>
            <div class="text">已支付</div>
          </div>
          <div class="arrow">→</div>
          <div class="step" :class="{ active: order.status === 3 }">
            <div class="icon">🛑</div>
            <div class="text">已取消</div>
          </div>
        </div>

        <div class="status-hints">
          <p v-if="order.status === 1" class="hint hint--pending">
            当前订单处于待支付状态。请在规定时间内完成支付，逾期系统将自动取消并释放座位。
          </p>
          <p v-else-if="order.status === 2" class="hint hint--paid">
            订单已支付。请妥善保管取票信息，届时凭有效证件或电子票入场。
          </p>
          <p v-else-if="order.status === 3" class="hint hint--canceled">
            订单已取消。已恢复可售座位，优惠券（如有）不再占用。
          </p>
        </div>

        <div class="detail-row">
          <span class="label">订单号：</span>
          <span class="value">{{ order.orderNo }}</span>
        </div>
        <div class="detail-row">
          <span class="label">状态：</span>
          <span class="value">{{ statusText(order.status) }}</span>
        </div>
        <div class="detail-row">
          <span class="label">演出：</span>
          <span class="value">
            <RouterLink :to="`/event/${order.eventId}`">查看演出详情</RouterLink>
          </span>
        </div>
        <div class="detail-row">
          <span class="label">票数：</span>
          <span class="value">{{ order.ticketCount }}</span>
        </div>
        <div class="detail-row">
          <span class="label">总金额：</span>
          <span class="value">¥{{ order.totalAmount }}</span>
        </div>
        <div class="detail-row">
          <span class="label">创建时间：</span>
          <span class="value">{{ formatDate(order.createdAt) }}</span>
        </div>

        <div class="detail-row" v-if="order.paymentMethod">
          <span class="label">支付方式：</span>
          <span class="value">{{ order.paymentMethod }}</span>
        </div>
        <div class="detail-row" v-if="order.paymentTime">
          <span class="label">支付时间：</span>
          <span class="value">{{ formatDate(order.paymentTime) }}</span>
        </div>

        <div class="detail-row">
          <span class="label">联系人：</span>
          <span class="value">{{ order.contactName }}</span>
        </div>
        <div class="detail-row">
          <span class="label">联系电话：</span>
          <span class="value">{{ order.contactPhone }}</span>
        </div>
        <div class="detail-row" v-if="order.contactEmail">
          <span class="label">联系邮箱：</span>
          <span class="value">{{ order.contactEmail }}</span>
        </div>

        <div class="items">
          <h2>票据</h2>
          <ul>
            <li v-for="(it, idx) in order.items" :key="`${it.ticketId}-${idx}`">
              票ID：{{ it.ticketId }}，单价：¥{{ it.price }}
            </li>
          </ul>
        </div>

        <div class="actions">
          <button class="btn btn--secondary" @click="back">返回订单列表</button>
          <button v-if="order.status === 1" class="btn btn--danger" @click="cancel">取消订单</button>
          <button v-if="order.status === 1" class="btn btn--primary" @click="pay">伪支付</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { apiClient } from '@/api/client'

const route = useRoute()
const router = useRouter()

const order = ref(null)
const loading = ref(false)
const error = ref('')

function statusText(s) {
  return s === 1 ? '待支付' : s === 2 ? '已支付' : s === 3 ? '已取消' : '未知'
}

function formatDate(dt) {
  if (!dt) return ''
  const d = new Date(dt)
  return d.toLocaleString('zh-CN')
}

async function load() {
  const orderNo = route.params.orderNo
  try {
    loading.value = true
    error.value = ''
    const resp = await apiClient.get(`/api/orders/${orderNo}`)
    const raw = resp?.data ?? resp ?? null
    order.value = normalizeOrder(raw)
  } catch (err) {
    if (String(err.message).includes('401')) {
      router.push(`/login?redirect=/order/${orderNo}`)
      return
    }
    error.value = `加载失败：${err.message}`
    console.error('加载订单详情失败', err)
  } finally {
    loading.value = false
  }
}

async function cancel() {
  try {
    await apiClient.post(`/api/orders/${order.value.orderNo}/cancel`, {})
    await load()
  } catch (err) {
    alert(`取消失败：${err.message}`)
  }
}

async function pay() {
  try {
    await apiClient.post(`/api/orders/${order.value.orderNo}/pay`, {})
    await load()
  } catch (err) {
    alert(`支付失败：${err.message}`)
  }
}

function back() {
  router.push('/orders')
}

onMounted(load)

function normalizeOrder(o) {
  if (!o) return null
  const items = Array.isArray(o.items)
    ? o.items.map(it => ({
        ticketId: it.ticketId ?? it.id ?? it.ticket?.id ?? '',
        price: it.price ?? it.amount ?? it.ticketPrice ?? 0
      }))
    : Array.isArray(o.tickets)
      ? o.tickets.map(t => ({ ticketId: t.id ?? t.ticketId ?? '', price: t.price ?? t.amount ?? 0 }))
      : []

  const status = typeof o.status === 'number'
    ? o.status
    : String(o.status || '').toUpperCase() === 'PAID'
      ? 2
      : String(o.status || '').toUpperCase() === 'CANCELED'
        ? 3
        : 1

  const totalAmount = o.totalAmount ?? o.amount ?? o.totalPrice ?? items.reduce((s, it) => s + (Number(it.price) || 0), 0)

  return {
    orderNo: o.orderNo ?? o.orderId ?? o.id ?? '',
    status,
    eventId: o.eventId ?? o.event?.id ?? '',
    ticketCount: o.ticketCount ?? o.itemCount ?? items.length,
    totalAmount,
    createdAt: o.createdAt ?? o.createTime ?? o.createdTime ?? o.created_at ?? '',
    paymentMethod: o.paymentMethod ?? o.payment?.method ?? '',
    paymentTime: o.paymentTime ?? o.payment?.time ?? '',
    contactName: o.contactName ?? o.contact?.name ?? '',
    contactPhone: o.contactPhone ?? o.contact?.phone ?? '',
    contactEmail: o.contactEmail ?? o.contact?.email ?? '',
    items
  }
}
</script>

<style lang="scss" scoped>
@use '@/assets/styles/variables' as *;

.order-detail {
  padding: $spacing-xl 0;
}
.status-flow {
  display: flex;
  align-items: center;
  gap: $spacing-md;
  margin-bottom: $spacing-md;
}
.step {
  display: flex;
  align-items: center;
  gap: $spacing-xs;
  padding: 8px 12px;
  border-radius: $border-radius-sm;
  background: #f5f5f7;
  color: $text-secondary;
}
.step.active {
  background: #e8f0fe;
  color: #1a73e8;
  font-weight: 600;
}
.step.done {
  opacity: 0.7;
}
.arrow {
  color: $text-secondary;
}
.status-hints {
  margin-bottom: $spacing-md;
}
.hint {
  padding: 10px 12px;
  border-radius: $border-radius-sm;
  background: #fafafa;
}
.hint--pending { border-left: 4px solid #fb8c00; }
.hint--paid    { border-left: 4px solid #43a047; }
.hint--canceled{ border-left: 4px solid #e53935; }
.detail-card {
  background: #fff;
  border-radius: $border-radius-md;
  box-shadow: $shadow-light;
  padding: $spacing-lg;
}
.detail-row {
  display: flex;
  gap: $spacing-sm;
  margin-bottom: $spacing-sm;
}
.label {
  color: $text-secondary;
}
.value {
  color: $text-primary;
}
.items {
  margin-top: $spacing-md;
}
.actions {
  display: flex;
  gap: $spacing-sm;
  margin-top: $spacing-lg;
}
.error {
  color: #d32f2f;
  margin-bottom: $spacing-md;
}
.empty {
  color: $text-secondary;
}
</style>